import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Dialog, DialogTitle, DialogContent, Button, FormControlLabel, Switch } from '@mui/material';
import "./Feeding.css"

const AddEquipmentDialog = ({ open, onClose, fetchData }) => {
    const [equipmentName, setEquipmentName] = useState("");
    const [equipmentCode, setEquipmentCode] = useState("");
    const [equipmentId, setEquipmentId] = useState("");
    const [modeId, setModeId] = useState(1);
    const [subtypeId, setSubtypeId] = useState("");
    const [typeId, setTypeId] = useState("");
    const [modes, setModes] = useState([{id: 1, name: "В штатном режиме"}, {id: 2, name: "Максимальная нагрузка"}, {id: 3, name: "Отключен"}])
    const [subtypes, setSubtypes] = useState([]);
    const [types, setTypes] = useState([]);
    const [on, setOn] = useState(true);
    const [comment, setComment] = useState("");


    useEffect(() => {
        fetchTypes();
    }, []);

    const handleComment = (event) => {
        setComment(event.target.value);
    };

    useEffect(() => {
        fetchSubtypes();
        if(typeId === ""){
            setSubtypes([])
        }
    }, [typeId]);


    const fetchSubtypes = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/subtypes${typeId!== ""? "?types="+typeId:""}`, {headers});
            setSubtypes(response.data.subtypes);
        } catch (error) {
            console.error('Error fetching subtypes:', error);
        }
    };
    const fetchTypes = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/types`, {headers});
            setTypes(response.data.typess);
        } catch (error) {
            console.error('Error fetching subtypes:', error);
        }
    };

    const addEquipment = async () => {
        try {
            const newEquipment = {
                "ename": equipmentName,
                "id_mode": modeId,
                "id_subtypes": subtypeId, 
                "on": on,
                "code": equipmentCode, 
                "comment": comment
            }
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            await axios.post(`${process.env.REACT_APP_API_BASE_URL}/equipment`, newEquipment, {headers});
            fetchData();
            onClose();
        } catch (error) {
            console.error('Error adding new equipment:', error);
        }
    };

    const handleModeChange = (event) => {
        setModeId(event.target.value);
    };

    const handleSubtypeChange = (event) => {
        setSubtypeId(event.target.value);
    };

    const handleTypeChange = (event) => {
        setTypeId(event.target.value);
    };

    const handleInputChangeName = (event) => {
        setEquipmentName(event.target.value);
    };
    const handleInputChangeCode = (event) => {
        setEquipmentCode(event.target.value);
    };

    const handleInputChangeId = (event) => {
        setEquipmentId(event.target.value);
    };

    return (
        <Dialog open={open} onClose={onClose} sx={{ '& .MuiDialog-paper': { width: '80%', maxWidth: 'none' } }}>
            <DialogTitle>Добавить новые данные об оборудовании</DialogTitle>
            <DialogContent>
                <div>
                    <div className='input-table-container'>
                    <div style={{ display: 'grid', gridTemplateColumns: "1.55fr 0.5fr 1fr", gap: '200px 20px' }}>
                            <FormControlLabel
                                control={
                                    <Switch
                                        checked={on}
                                        onChange={() => {setOn(!on)}}
                                    />
                                }
                                label={on? "Оборудование подключено":"Оборудование выключено"}
                                sx={{
                                    '& .MuiFormControlLabel-label': {
                                        fontFamily: 'Montserrat', fontWeight: 'bolder',
                                    }
                                }}
                            />
                            <label>Код</label>
                            <input className='input-form-table'
                                type={"text"}
                                value={equipmentCode}
                                onChange={handleInputChangeCode}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            <label>Наименование оборудования</label>
                            <input className='input-form-table'
                                type={"text"}
                                value={equipmentName}
                                onChange={handleInputChangeName}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            />
                            <label>Режим работы</label>
                            <select
                                value={modeId}
                                onChange={handleModeChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                {modes.map(mode => (
                                    <option key={mode.id} value={mode.id}>{mode.name}</option>
                                ))}
                            </select>
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.5fr 1fr 0.5fr 1fr", gap: '20px' }}>
                            
                            <label>Тип</label>
                            <select
                                value={typeId}
                                onChange={handleTypeChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                            >
                                <option key={""} value="">Выберите тип</option>
                                {types.map(subtype => (
                                    <option key={subtype.id} value={subtype.id}>{subtype.tname}</option>
                                ))}
                            </select>
                            <label>Подтип</label>
                            <select
                                value={subtypeId}
                                onChange={handleSubtypeChange}
                                style={{ borderColor: '#003AD0', margin: 0, width: '100%' }}
                                disabled={typeId===""}
                            >
                                <option key={""} value="">Выберите подтип</option>
                                {subtypes.map(subtype => (
                                    <option key={subtype.id} value={subtype.id}>{subtype.name}</option>
                                ))}
                            </select>
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: "0.2fr 1fr", gap: '10px' }}>
                            <label>Комментарий</label>
                            <textarea
                                className='input-form-table'
                                type="text"
                                value={comment}
                                onChange={handleComment}
                                style={{ borderColor: '#003AD0', margin: 0, width: '90%', maxWidth: '1400px' }}
                                required={true}
                            />
                        </div>
                        <Button onClick={addEquipment} sx={{ margin: 3, width: '95%', color: 'white', borderRadius: '15px', backgroundColor: '#003AD0', '&:focus': { backgroundColor: '#003AD0' }, fontStyle: { fontColor: 'white', fontSize: 20, fontWeight: 'bolder', fontFamily: "Montserrat" } }} variant={'contained'}>
                            Сохранить
                        </Button>
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
};

export default AddEquipmentDialog;
